<template>
  <view class="config-container">
    <view class="form">
      <view class="form-item">
        <text>WiFi名称</text>
        <input v-model="ssid" placeholder="请输入WiFi名称" />
      </view>
      <view class="form-item">
        <text>WiFi密码</text>
        <input v-model="password" type="password" placeholder="请输入WiFi密码" />
      </view>
      <button class="submit-btn" @click="startConfig">开始配网</button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import {onLoad } from '@dcloudio/uni-app';
import { ref, reactive, onMounted, onUnmounted } from 'vue';

import { writeData, getType, isSubcontractor, getFrameCTRLValue, hexByInt } from '@/utils/blufi';

// 路由参数
const deviceId = ref<string>('');
const serviceId = ref<string>('');
const writeCharId = ref<string>('');
const readCharId = ref<string>('');

// 表单数据
const ssid = ref<string>('');
const password = ref<string>('');

// 全局配置
const PACKAGE_VALUE = 0x01;
const SUBTYPE_SET_SSID = 0x2;
const SUBTYPE_SET_PWD = 0x3;
const SUBTYPE_END = 0x03;

// 配网状态
const sequence = ref<number>(0); // 序列号

// 获取路由参数
onLoad((options) => {
  if (options?.deviceId && options?.serviceId && options?.writeCharId && options?.readCharId) {
    deviceId.value = options.deviceId;
    serviceId.value = options.serviceId;
    writeCharId.value = options.writeCharId;
    readCharId.value = options.readCharId;
    console.log('获取到路由参数:', options);
  } else {
    console.error('路由参数缺失:', options);
    uni.showToast({ title: '参数缺失', icon: 'none' });
    setTimeout(() => uni.navigateBack(), 2000);
  }
});

// 写入蓝牙数据
const writeBLEData = async (data: number[]) => {
  return new Promise<void>((resolve, reject) => {
    uni.writeBLECharacteristicValue({
      deviceId: deviceId.value,
      serviceId: serviceId.value,
      characteristicId: writeCharId.value,
      value: new Uint8Array(data).buffer,
      success: () => {
        console.log('写入数据:', data);
        resolve();
      },
      fail: (err) => {
        console.error('写入失败:', err);
        reject(err);
      },
    });
  });
};

// 开始配网
const startConfig = async () => {
  if (!ssid.value || !password.value) {
    uni.showToast({ title: '请输入WiFi名称和密码', icon: 'none' });
    return;
  }

  uni.showLoading({ title: '配网中...' });

  try {
    // 启用通知
    await uni.notifyBLECharacteristicValueChange({
      deviceId: deviceId.value,
      serviceId: serviceId.value,
      characteristicId: readCharId.value,
      state: true,
    });

    // 发送SSID
    const ssidData = hexByInt(Buffer.from(ssid.value).toString('hex'));
    const ssidPacket = writeData(
      PACKAGE_VALUE,
      SUBTYPE_SET_SSID,
      getFrameCTRLValue(false, false, 0, false, false),
      sequence.value++,
      ssidData.length,
      ssidData
    );
    const ssidSub = isSubcontractor(ssidPacket, false, sequence.value, false);
    await writeBLEData(ssidSub.lenData);

    // 发送密码
    const pwdData = hexByInt(Buffer.from(password.value).toString('hex'));
    const pwdPacket = writeData(
      PACKAGE_VALUE,
      SUBTYPE_SET_PWD,
      getFrameCTRLValue(false, false, 0, false, false),
      sequence.value++,
      pwdData.length,
      pwdData
    );
    const pwdSub = isSubcontractor(pwdPacket, false, sequence.value, false);
    await writeBLEData(pwdSub.lenData);

    // 发送结束标志
    const endPacket = writeData(
      PACKAGE_VALUE,
      SUBTYPE_END,
      getFrameCTRLValue(false, false, 0, false, false),
      sequence.value++,
      0,
      null
    );
    await writeBLEData(endPacket);

    // 监听配网结果
    await waitForConfigResult();
  } catch (err) {
    console.error('配网失败:', err);
    uni.hideLoading();
    uni.showToast({
      title: '配网失败',
      icon: 'none',
      duration: 2000,
      success: () => {
        setTimeout(() => {
          uni.navigateBack(); // 返回设备列表
        }, 2000);
      },
    });
  }
};

// 监听配网结果
const waitForConfigResult = () => {
  return new Promise<void>((resolve, reject) => {
    uni.onBLECharacteristicValueChange((res) => {
      const value = new Uint8Array(res.value);
      const type = value[0] & 0x03;
      const subType = (value[0] >> 2) & 0x3F;
      console.log('收到通知:', { type, subType, value });

      if (type === PACKAGE_VALUE && subType === 15) {
        // 配网成功
        uni.hideLoading();
        uni.showToast({
          title: '配网成功',
          icon: 'success',
          duration: 2000,
          success: () => {
            setTimeout(() => {
              uni.navigateBack({ delta: 2 }); // 返回设备列表
            }, 2000);
          },
        });
        resolve();
      } else if (type === PACKAGE_VALUE && subType === 18) {
        // 配网失败
        reject(new Error('配网失败'));
      }
    });

    // 超时处理
    setTimeout(() => {
      reject(new Error('配网超时'));
    }, 20000); // 20秒超时
  });
};

// 页面加载
onMounted(() => {
  uni.setNavigationBarTitle({ title: '设备配网' });
});

// 页面卸载
onUnmounted(() => {
  uni.closeBLEConnection({ deviceId: deviceId.value });
  uni.offBLECharacteristicValueChange();
});
</script>

<style scoped>
.config-container {
  padding: 40rpx;
}
.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 40rpx;
}
.form-item text {
  width: 150rpx;
  font-size: 32rpx;
}
.form-item input {
  flex: 1;
  border: 1rpx solid #ccc;
  padding: 10rpx;
  border-radius: 10rpx;
}
.submit-btn {
  background: #007AFF;
  color: #fff;
  font-size: 32rpx;
  padding: 20rpx;
  border-radius: 10rpx;
  text-align: center;
}
</style>